<template>
  <div class="container">
    <el-form ref="ruleForm" :model="query" :rules="rules" label-width="120px">
      <el-form-item label="公告名称" prop="noticeName">
        <el-input
              maxlength="50"
          v-model="query.noticeName"
          placeholder="请输入公告名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="原文链接" prop="noticeCategory">
        <el-input
              maxlength="50"
          v-model="query.noticeCategory"
          placeholder="请输入原文链接"
        ></el-input>
      </el-form-item>

      <el-form-item label="概要" prop="noticeSummary">
        <el-input
              maxlength="50"
          v-model="query.noticeSummary"
          placeholder="请输入概要"
        ></el-input>
      </el-form-item>
      <el-form-item label="公告内容" prop="noticeContent">
        <quill-editor
          :content="query.noticeContent"
          :options="editorOption"
          @change="onEditorChange($event)"
        />
      </el-form-item>
      <el-form-item label="相关附件">
        <el-upload
          :file-list="query.list"
          drag
          :action="$upload"
            :headers="$headers()"
          :on-preview="
            (e) => {
              $downloadFiles(e.fileUrl);
            }
          "
          :on-error="onError"
          :on-remove="onRemove"
          :before-remove="beforeRemove"
          multiple
          :on-success="success"
          :before-upload="
            (e) => {
              return $beforeAvatarUpload(e, 1);
            }
          "
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传world、excel、pdf文件，且不超过5M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="">
        <div class="form_button">
          <el-button type="primary" @click="submit(0)">仅保存</el-button>
          <el-button type="primary" @click="submit(1)">保存并下发</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { quillRedefine } from "vue-quill-editor-upload";
import { timestamp } from "@/utils/token"
export default {
  created() {
    // let data = JSON.parse(sessionStorage.getItem("notice"));
    // console.log(data);
    // if (data) {
    //   this.query.id = data.id;
    //   this.query.noticeCategory = data.noticeCategory;
    //   this.query.creaeUnitId = data.creaeUnitId;
    //   this.query.creaeUnitName = data.creaeUnitName;
    //   this.query.noticeContent = data.noticeContent;
    //   this.query.noticeName = data.noticeName;
    // }
    if(this.$route.query.id){
        this.findById(this.$route.query.id)
    }
    let that = this;
    this.editorOption = quillRedefine({
      // 图片上传的设置
      uploadConfig: {
        action: that.$upload, // 必填参数 图片上传地址
        // 必选参数  res是一个函数，函数接收的response为上传成功时服务器返回的数据
        // 你必须把返回的数据中所包含的图片地址 return 回去
        res: (respnse) => {
          if (respnse.code == 200) {
            return that.$uploadURL + respnse.data;
          } else {
            that.$error("上传失败");
          }
        },
        methods: "POST", // 可选参数 图片上传方式  默认为post
        token: "", // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
        name: "file", // 可选参数 文件的参数名 默认为img
        size: 5 * 1024, // 可选参数   图片限制大小，单位为Kb, 1M = 1024Kb
        accept: "image/png,image/jpeg, ", // 可选参数 可上传的图片格式
        // start: function (){}
        start: (e) => {}, // 可选参数 接收一个函数 开始上传数据时会触发
        end: (e) => {}, // 可选参数 接收一个函数 上传数据完成（成功或者失败）时会触发
        success: (e) => {}, // 可选参数 接收一个函数 上传数据成功时会触发
        error: () => {}, // 可选参数 接收一个函数 上传数据中断时会触发
           header: (xhr) => {
                //关键是这句话
                   xhr.setRequestHeader('timestamp',timestamp());
                                return xhr
               //    Authorization:localStorage.getItem("sessionKey")
               },  // 可选参数 设置请求头部,
      },
      // 以下所有设置都和vue-quill-editor本身所对应
      placeholder: "请输入编辑文章内容", // 可选参数 富文本框内的提示语
      theme: "", // 可选参数 富文本编辑器的风格
      toolOptions: [
        ["bold", "italic", "underline", "strike"],
        ["blockquote", "code-block"],
        [{ header: 1 }, { header: 2 }],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ script: "sub" }, { script: "super" }],
        [{ indent: "-1" }, { indent: "+1" }],
        [{ direction: "rtl" }],
        [{ size: ["small", false, "large", "huge"] }],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ color: [] }, { background: [] }],
        [{ font: [] }],
        [{ align: [] }],
        ["clean"],
        ["link", "image"],
      ], // 可选参数  选择工具栏的需要哪些功能  默认是全部
      handlers: {},
    });
  },
  data() {
    return {
      form: {
        name: "",
        type: [],
      },
      content: "",
      editorOption: {},
      query: {
        creaeUnitId: 23342113,
        creaeUnitName: "苏州市市场监督管理局",
        id: "",
        list: [],
        noticeCategory: "",
        noticeContent: "",
        noticeName: "",
        noticeState: 0,
        noticeSummary:"",
      },
      bodyIndustryAll: false,
      areaAll: false,
      rules: {
        noticeName: [
          { required: true, message: "请输入公告名称", trigger: "blur" },
        ],
        noticeContent: [
          {
            required: true,
            message: "请输入公告内容",
            trigger: "blur",
          },
        ],
    noticeSummary: [
          {
            required: true,
            message: "请输入概要",
            trigger: "blur",
          },
        ],
        
      },
    };
  },
  methods: {
    onEditorChange(e) {
      this.query.noticeContent = e.html;
    },
    success(e) {
      // this.$closeLoading&&this.$closeLoading.close()
      if (e.code == 200) {
        this.query.list.push({
          name: this.$imageName,
          fileName: this.$imageName,
          fileUrl: this.$uploadURL + e.data,
          url: this.$uploadURL + e.data,
        });
      }
    },
    onError() {
      this.$error("上传失败");
    },
    onRemove(e) {
      this.query.list = this.query.list.filter((x) => x.uid != e.uid);
    },
    beforeRemove(file) {
      if (file && file.status === "success") {
        return this.$confirm("确定删除这个文件吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
      }
    },
    submit(type) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
            this.query.noticeState = type;
          //   this.query.unitModuleTaskAreaSaveRequestList = [];
          //   this.query.unitModuleTaskFormatSaveRequestList = [];
          //   this.query.areaList.forEach(x => {
          //     if (this.query.area.includes(x.areaName)) {
          //       this.query.unitModuleTaskAreaSaveRequestList.push({
          //         areaCode: x.areaCode,
          //         areaName: x.areaName,
          //       });
          //     }
          //   });
          //   this.query.bodyIndustryList.forEach(x => {
          //     if (this.query.bodyIndustry.includes(x.bodyIndustryRemarks)) {
          //       this.query.unitModuleTaskFormatSaveRequestList.push({
          //         bodyIndustry: x.bodyIndustry,
          //         bodyIndustryRemarks: x.bodyIndustryRemarks,
          //         isSpecialFood: x.isSpecialFood,
          //       });
          //     }
          //   });
          if (this.query.id) {
            this.$http
              .updateNotice(this.query)
              .then((res) => {
                  this.$success("保存成功");
                  this.$router.go(-1);
              })
          } else {
            this.$http
              .saveFoodSafetyNotice(this.query)
              .then((res) => {
                  this.$success("保存成功");
                  // this.$router.push('/task');
                  this.$router.go(-1);
           
              })
          }
        } else {
          this.$error("请输入必填项");
        }
      });
    },
    findById(id){
      this.$http
              .findById({
                params:{
                  id,
                }
              })
              .then((res) => {
                    console.log(res.data);
res.data.list.forEach(x=>{
    x.name=x.fileName
  })
  this.query.creaeUnitId=res.data.creaeUnitId
  this.query.creaeUnitName=res.data.creaeUnitName
  this.query.id=res.data.id
  this.query.noticeCategory=res.data.noticeCategory
  this.query.noticeContent=res.data.noticeContent
  this.query.noticeName=res.data.noticeName
  this.query.list=res.data.list

           this.query.noticeSummary = res.data.noticeSummary;
              })
    },
  },
  // 监听属性
  watch: {},
  //实例销毁之前
  beforeDestroy() {
    sessionStorage.removeItem("notice");
  },
};
// query.area
</script>
<style lang="less" scoped>
.container {
  padding: 20px;
  .checkbox {
    display: flex;
    .checkbox_last {
      margin-right: 15px;
    }
  }
  .form_button {
    text-align: right;
  }
   /deep/ .ql-container {
    font-size: 16px;
  }
}
</style>
